package cc.rengu.igas.channel.wechat.core.packswitch;

import cc.rengu.igas.channel.wechat.common.constant.WechatParamConstant;
import cc.rengu.igas.channel.wechat.common.constant.WechatTreeNodeConstant;
import cc.rengu.igas.channel.wechat.common.constant.WechatTxnNumConstant;
import cc.rengu.jradp.packetswitch.IncomingPackSwitchImpl;
import cc.rengu.jradp.packetswitch.OutgoingPackSwitchImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.RandomUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

/**
 * 与微信公众号通讯层报文解包前后、组前包后实现类
 * Created by 王成 on 2018/5/29.
 */
public class WechatPublicServerPackSwitch implements IncomingPackSwitchImpl, OutgoingPackSwitchImpl {

    @Override
    public byte[] beforeInComPackSwitch(byte[] bytes) throws Exception {
        return bytes;
    }

    @Override
    public int afterInComPackSwitch() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.INST_ID, AppParamConstant.DEFAULT_INSTID);
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.MSG_SRC_ID, WechatParamConstant.TUNL_ID_WXZF);
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.BIZ_TYPE, AppParamConstant.DEFAULT_BIZ_TYPE);
        xmlTreeUtil.setXmlTreeStringValue(AppParamConstant.SYS_ID, WechatParamConstant.TUNL_ID_WXZF);
        if (xmlTreeUtil.isExist(WechatTreeNodeConstant.WX_MSG_ID)) {
            xmlTreeUtil.copyStringValue(WechatTreeNodeConstant.WX_MSG_ID, TreeNodeConstant.FRONT_SEQ_NUM);
        } else {
            String frontSeqNum = WechatParamConstant.PREFIX_SEQ_STRING + DateUtil.getCurrentDate() + DateUtil.getCurrentTime() + RandomUtil.getRandomInt();
            xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.FRONT_SEQ_NUM, frontSeqNum);
        }
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, WechatTxnNumConstant.T00CH201);
        return 0;
    }

    @Override
    public int beforeOutgoPackSwitch() throws Exception {
        return 0;
    }

    @Override
    public byte[] afterOutgoPackSwitch(byte[] bytes) throws Exception {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        if (null == bytes || 2 >= bytes.length) {
            return new byte[0];
        } else {
            String sendMsg = new String(bytes);
            rglog.info("发送的报文内容为：<{}>", sendMsg);
            return bytes;
        }
    }
}
